/**
 * @file SSEManager 连接管理组件
 * @date 2025/11/20 14:54:19
 * @author lyqjob@yeah.net
 * @description 负责建立和管理 SSE 连接，处理各种 SSE 事件
 */

import { useEffect, useMemo } from 'react';
import { Modal, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import useSSE from '@/hooks/useSSE';
import { useClientId } from '@/hooks/useClientId';
import { useAuth } from '@/hooks/useAuth';



const SSEManager = () => {
    const navigate = useNavigate();
    const clientId = useClientId();
    const { handleLogout } = useAuth();
    const [api, contextHolder] = message.useMessage();
    const openMessage = (type, content) => {
        api[type](content);
    };

    // 构建 SSE URL
    const sseurl = useMemo(() => {
        const base = process.env.NODE_ENV === 'production'
            ? 'https://admin.liyq666.top/sse/connect/auth'
            : 'http://localhost:8888/sse/connect/auth';
        const sep = base.includes('?') ? '&' : '?';
        return `${base}${sep}clientId=${encodeURIComponent(clientId)}`;
    }, [clientId]);

    const { subscribe } = useSSE({
        url: sseurl,
        autoconnect: true,
        autoDisconnect: true,
        reconnectDelay: 3000,
        maxReconnectAttempts: Infinity,
        logEvents: process.env.NODE_ENV === 'development',
        useAuth: true,
        enableHeartbeat: true,
    });

    useEffect(() => {
        const unsubOpen = subscribe('open', (e) => {
            const data = JSON.parse(e?.data || '{}');
            const { connectionId } = data || {};
            if (connectionId) {
                openMessage('success', `SSE建立连接成功，连接ID: ${connectionId}`);
            }
        });

        const unsubWelcome = subscribe('welcome', () => {
            // 处理欢迎消息
        });

        const unsubHeartbeat = subscribe('heartbeat', () => {
            // 处理心跳包
        });

        const unsubLoginout = subscribe('loginout', () => {
            // 处理登录/退出事件
            Modal.warning({
                title: '登录异常',
                content: '您已在其他地方登录或被强制注销，当前登录已失效，请重新登录！',
                onOk() {
                    handleLogout();
                },
            });
        });

        const unsubMessage = subscribe('message', () => {
            // 处理普通消息
        });

        const unsubError = subscribe('error', (err) => {
            if (err && err.status === 401) {
                // 身份验证不通过，执行登出
                handleLogout();
            }
        });

        return () => {
            unsubOpen && unsubOpen();
            unsubWelcome && unsubWelcome();
            unsubHeartbeat && unsubHeartbeat();
            unsubLoginout && unsubLoginout();
            unsubMessage && unsubMessage();
            unsubError && unsubError();
        };
    }, [subscribe, handleLogout]);

    // SSEManager 是一个纯逻辑组件，不渲染任何 UI
    return contextHolder;
};

export default SSEManager;